<template>
  <div id="main">
    <h2>学生考勤管理</h2>
    <el-input v-model="searchTableInfo" placeholder="请输入搜索内容" style="width:240px;float: right;margin-top:0px;;margin-right:30px;" />
    <div style="margin:20px;">
      <el-form ref="attendanceStu" :model="attendanceStu" label-position="top">
        <el-row type="flex" justify="">
          <el-col :span="4">
            <el-form-item
              prop="studentId"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="attendanceStu.studentId"
                filterable
                placeholder="请选择要查看的学生"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in child"
                  :key="item.studentId"
                  :label="item.String"
                  :value="item.studentId"
                />
              </el-select>
            </el-form-item></el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              style="margin-left:10px"
              @click="handleSerch('attendanceStu')"
            >查询</el-button></el-col>

          <!-- </el-row>

      <el-row type="flex" justify=""> -->
          <el-col :span="5">
            <el-form-item
              prop="classId"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="attendanceStu.classId"
                filterable
                placeholder="请选择班级"
                style="width: 80%;"
              >
                <el-option
                  v-for="item in clazz"
                  :key="item.classId"
                  :label="item.className"
                  :value="item.classId"
                />
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item
              prop="completionTimes"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="attendanceStu.completionTimes"
                placeholder="请输入第几节课"
                autocomplete="off"
                maxlength="20"
                show-word-limit
                style="width: 80%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              style="margin-top:0px"
              @click="handleClass(attendanceStu)"
            >查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="studentName"
          label="学生姓名"
          width="120"
        />
        <el-table-column
          align="center"
          prop="className"
          label="班级"
          width="120"
        />
        <el-table-column
          align="center"
          prop="staffName"
          label="责任老师"
          width="120"
        />
        <el-table-column
          align="center"
          prop="attStatus"
          label="出勤情况"
          width="120"
        />

        <el-table-column
          align="center"
          prop="completionTimes"
          label="上课次数"
          width="100"
        />
        <el-table-column
          align="center"
          prop="reasonAbsence"
          label="缺勤原因"
        />
        <el-table-column
          align="center"
          prop="postTime"
          label="打卡时间"
          width="160"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改考勤', 2, Scope.row.attStuId)"
            >编辑</el-button>
            <!-- <el-button
              type="danger"
              icon="el-icon-delete"
              @click="
                handleDelete(Scope.row.attStuId)
              "
            >删除</el-button> -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="
                openAdult(Scope.row.attStuId)
              "
            >审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog title="" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form
        ref="attendanceStu"
        :model="attendanceStu"
        label-position="top"
        :rules="rules"
      >
        <el-form-item
          prop="classId"
          label="班级名称"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="attendanceStu.classId"
            filterable
            placeholder="请选择"
            style="width: 40%;"
            @change="getstudents"
          >
            <el-option
              v-for="item in clazz"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="studentId"
          label="学生姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="attendanceStu.studentId"
            filterable
            placeholder="请选择"
            style="width: 40%;"
          >
            <el-option
              v-for="item in child"
              :key="item.studentId"
              :label="item.String"
              :value="item.studentId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="teacherId"
          label="教师姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="attendanceStu.teacherId"
            filterable
            placeholder="请选择"
            style="width: 40%;"
          >
            <el-option
              v-for="item in teacher"
              :key="item.staffId"
              :label="item.String"
              :value="item.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="attendance"
          label="出勤情况"
          :label-width="formLabelWidth"
        >
          <el-select v-model="attendanceStu.attendance" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="attendanceStu.attendance == 0"
          prop="reasonAbsence"
          label="缺勤原因"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="attendanceStu.reasonAbsence"
            autocomplete="off"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          v-if="attendanceStu.attendance == 0"
          prop="abnormalSituation"
          label="情况说明"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="attendanceStu.abnormalSituation"
            autocomplete="off"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          v-if="attendanceStu.attendance == 0"
          prop="abnormalRelevantMatters"
          label="相关事宜"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="attendanceStu.abnormalRelevantMatters"
            autocomplete="off"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          v-if="attendanceStu.attendance == 0"
          prop="abnormalAdult"
          label="审批说明"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="attendanceStu.abnormalAdult"
            autocomplete="off"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('attendanceStu')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddUser('attendanceStu')"
        >添 加</el-button>
      </div>
    </el-dialog>

    <el-dialog title="" :close-on-click-modal="false" :visible.sync="adultFormVisible" :before-close="handleClose2">
      <el-form ref="adult" :model="adult" label-position="top" :rules="rules">

        <el-form-item prop="abnormalSituation" label="情况说明" :label-width="formLabelWidth">
          <el-input v-model="adult.abnormalSituation" autocomplete="off" maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item prop="abnormalRelevantMatters" label="相关事宜" :label-width="formLabelWidth">
          <el-input v-model="adult.abnormalRelevantMatters" autocomplete="off" maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item prop="abnormalAdult" label="审批说明" :label-width="formLabelWidth">
          <el-input v-model="adult.abnormalAdult" autocomplete="off" maxlength="30" show-word-limit />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doAdult()">提 交</el-button>
        <el-button type="primary" @click="handleClose2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  updateAttById,
  deleteAtt,
  getAllAtt,
  addoneAtt,
  getAttbyId,
  getStudentString,
  getTeacherString,
  getClassString,
  getAllStudentString,
  SerchByIdData,
  SerchClassByIdData,
  adultById
} from '@/api/attendanceStu'
export default {
  data() {
    return {
      options: [
        {
          value: 1,
          label: '出勤'
        },
        {
          value: 0,
          label: '缺勤'
        }
      ],
      newAtt: {
        attStuId: '',
        studentName: '',
        className: '',
        attStatus: '',
        staffName: '',
        completionTimes: '',
        reasonAbsence: '',
        postTime: ''
      },
      value: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      // list: [],
      tableList: [],
      searchTableInfo: '',
      attendanceStu: [],
      listLoading: false,
      dialogFormVisible: false,
      adultFormVisible: false,
      editType: 1, // 1 添加 2 修改
      adult: {},
      child: {},
      teacher: {},
      clazz: {},
      search: '',
      formLabelWidth: '200px',
      rules: {
        attendance: [
          { required: true, message: '出勤情况不能为空', trigger: 'blur' }
        ],
        classId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],

        studentId: [
          { required: true, message: '学生姓名不能为空', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '教师姓名不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.fetchData()
    this.getAllTeacher()
    this.getAllClass()
    this.getAllChildString()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },

    // SerchByIdData(id) {
    //   SerchByIdData(id).then(res => {
    //     this.tableList = res.obj
    //   })
    // },
    getAllChild(id) {
      getStudentString(id).then(res => {
        this.child = res.obj
      })
    },
    getAllChildString() {
      getAllStudentString().then(res => {
        this.child = res.obj
      })
    },
    getAllTeacher() {
      getTeacherString().then(res => {
        this.teacher = res.obj
      })
    },
    getAllClass() {
      getClassString().then(res => {
        this.clazz = res.obj
      })
    },
    handleClick(row) {
      console.log(row)
    },

    handleClass(attendanceStu) {
      this.tableList = []
      this.listLoading = true
      SerchClassByIdData(attendanceStu).then(data => {
        this.newAtt
        for (var i = 0; i < data.obj.length; i++) {
          this.newAtt.attStuId = data.obj[i].attStuId
          this.newAtt.studentName = data.obj[i].student.studentName
          this.newAtt.className = data.obj[i].clazz.className
          this.newAtt.staffName = data.obj[i].staff.staffName
          this.newAtt.completionTimes = data.obj[i].completionTimes
          this.newAtt.reasonAbsence = data.obj[i].reasonAbsence
          if (data.obj[i].reasonAbsence === null) {
            this.newAtt.reasonAbsence = '已出勤'
          }
          this.newAtt.postTime = data.obj[i].postTime
          if (data.obj[i].attendance === 0) {
            this.newAtt.attStatus = '未出勤'
          }
          if (data.obj[i].attendance === 1) {
            this.newAtt.attStatus = '已出勤'
          }
          this.tableList.push(this.newAtt)
          this.newAtt = {}
        }
        this.listLoading = false
      })
    },

    handleSerch() {
      this.tableList = []
      this.listLoading = true
      SerchByIdData(this.attendanceStu.studentId).then(data => {
        this.newAtt
        for (var i = 0; i < data.obj.length; i++) {
          this.newAtt.attStuId = data.obj[i].attStuId
          this.newAtt.studentName = data.obj[i].student.studentName
          this.newAtt.className = data.obj[i].clazz.className
          this.newAtt.staffName = data.obj[i].staff.staffName
          this.newAtt.completionTimes = data.obj[i].completionTimes
          this.newAtt.reasonAbsence = data.obj[i].reasonAbsence
          if (data.obj[i].reasonAbsence === null) {
            this.newAtt.reasonAbsence = '已出勤'
          }
          this.newAtt.postTime = data.obj[i].postTime
          if (data.obj[i].attendance === 0) {
            this.newAtt.attStatus = '未出勤'
          }
          if (data.obj[i].attendance === 1) {
            this.newAtt.attStatus = '已出勤'
          }
          this.tableList.push(this.newAtt)
          this.newAtt = {}
        }
        this.listLoading = false
      })
    },

    fetchData() {
      this.tableList = []
      this.listLoading = true
      getAllAtt().then(data => {
        this.newAtt
        for (var i = 0; i < data.obj.length; i++) {
          this.newAtt.attStuId = data.obj[i].attStuId
          this.newAtt.studentName = data.obj[i].student.studentName
          this.newAtt.className = data.obj[i].clazz.className
          this.newAtt.staffName = data.obj[i].staff.staffName
          this.newAtt.completionTimes = data.obj[i].completionTimes
          this.newAtt.reasonAbsence = data.obj[i].reasonAbsence
          if (data.obj[i].reasonAbsence === null) {
            this.newAtt.reasonAbsence = '已出勤'
          }
          this.newAtt.postTime = data.obj[i].postTime
          if (data.obj[i].attendance === 0) {
            this.newAtt.attStatus = '未出勤'
          }
          if (data.obj[i].attendance === 1) {
            this.newAtt.attStatus = '已出勤'
          }
          this.tableList.push(this.newAtt)
          this.newAtt = {}
        }
        this.listLoading = false
      })
    },
    handleDelete(id, username) {
      this.$confirm('确认删除该学生？').then(() =>
        deleteAtt(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil(
            (this.tableList.length - 1) / this.pagesize
          )
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },

    // handleSerch(formName) {
    //   console.log('确定按钮发送的信息', this.attendanceStu)
    //   this.tableList = []
    //   this.$refs[formName].validate(valid => {
    //     if (valid) {
    //       SerchByIdData(this.attendanceStu).then(resp => {
    //         this.tableList = resp.obj
    //         this.$notify({
    //           title: '操作成功',
    //           type: 'success'
    //         })
    //         //  this.fetchData()
    //       })
    //       this.attendanceStu = {}
    //       this.dialogFormVisible = false
    //       return true
    //     } else {
    //       this.$notify({
    //         title: '请正确填写',
    //         type: 'error'
    //       })
    //       return false
    //     }
    //   })
    // },
    handleAddUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addoneAtt(this.attendanceStu).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.attendanceStu = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.attendanceStu = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getAttbyId(id).then(resp => {
          this.attendanceStu = resp.obj
          this.attendanceStu.studentId = String(this.attendanceStu.studentId)
          getStudentString(this.attendanceStu.classId).then(resp => {
            this.child = resp.obj
          })
        })
      }
    },
    getstudents() {
      getStudentString(this.attendanceStu.classId).then(resp => {
        this.child = resp.obj
      })
      if (this.editType === 2) {
        this.attendanceStu.studentId = ''
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.attendanceStu = {}
    },
    handleClose2() {
      this.adultFormVisible = false
      this.adult = {}
    },
    attendance(row, column) {
      if (row.attendance === 0) {
        return '缺勤'
      }
      if (row.attendance === 1) {
        return '出勤'
      }
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          updateAttById(this.attendanceStu).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    openAdult(id) {
      getAttbyId(id).then(resp => {
        if (resp.obj.attendance === 1) {
          this.$notify({
            title: '该学生已出勤',
            type: 'warning'
          })
        } else {
          if (resp.obj.abnormalStatus === 1) {
            this.$notify({
              title: '该考勤已审核',
              type: 'warning'
            })
          } else {
            this.adult = {}
            this.adultFormVisible = true
            this.adult.id = id
          }
        }
      })
    },
    doAdult() {
      adultById(this.adult).then((resp) => {
        this.$notify({
          title: '审核成功',
          type: 'success'
        })
        this.fetchData()
      })
      this.adultFormVisible = false
    }
    // getAllJurisdiction() {
    //   getAllJurisdiction().then((resp) => {
    //     this.jurisdiction = resp.obj
    //   })
    // },
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
